﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Media;
using MEMORY_NEW;
using System.Reflection;


namespace MEMORY
{
    
    public partial class Form1 : Form
    {

        public List<MyPictureBox> list_box = new List<MyPictureBox>();
        public List<MyBitmap> list_bitmap = new List<MyBitmap>();
        Bitmap[] pictures = new Bitmap[16];

        public int user_pic = 0;
        int win = 0;

        public Form1()
        {
            InitializeComponent();
               
            pictures[0] = MEMORY.Properties.Resources._013;
            pictures[1] = MEMORY.Properties.Resources._0__1_;
            pictures[2] = MEMORY.Properties.Resources._1__2_;
            pictures[3] = MEMORY.Properties.Resources._1661_koshki;
            pictures[4] = MEMORY.Properties.Resources._29bu0MSwOXY;
            pictures[5] = MEMORY.Properties.Resources._31;
            pictures[6] = MEMORY.Properties.Resources._8;
            pictures[7] = MEMORY.Properties.Resources.applikatsyi_kartinki_iz_peska;
            pictures[8] = MEMORY.Properties.Resources.av_360672;
            pictures[9] = MEMORY.Properties.Resources.egik;
            pictures[10] = MEMORY.Properties.Resources.losyash;
            pictures[11] = MEMORY.Properties.Resources.m_ava;
            pictures[12] = MEMORY.Properties.Resources.picture_7601;
            pictures[13] = MEMORY.Properties.Resources.simon;
            pictures[14] = MEMORY.Properties.Resources.radiacia;
            pictures[15] = MEMORY.Properties.Resources.timthumb;
          
        }

        Random rand = new Random();
        string level = "easy";

        private void NewGame()
        {
            ClearAll();
            list_box.Clear();
            list_bitmap.Clear();
            switch (level)
            {
                case "easy":
                    Cells(4, 4);
                    break;
                case "average":
                    Cells(6, 4);
                    break;
                case "hard":
                    Cells(6, 5);
                    break;
            }
        }

        int[,] Random(int width, int height)
        {
            //тут будет разброс картинок по полю

            int S = width * height; //число ячеек (всего)
            int I = S / 2; // число картинок
            int[] cells=new int[S]; // массив ячеек
            int[,] images=new int[I,2]; // откомментироватть надо!!!!!! УБРАТЬ ИЗ ГЛОБАЛЬНОГО
            bool[] used = new bool[S]; //массив, показывающий какие ячейки использованы
            
            int r1 = 0;

            for (int i = 0; i < I; i++)
            {
                for (int j = 0; j < 2; j++) //на каждую картинку две ячейки
                {
                    r1 = rand.Next(0, S);
                       
                    while (used[r1] == true)
                    {
                        r1 = rand.Next(0, S);
                    }  
                  
                    used[r1] = true;
                    images[i, j] = r1;  
                }
            }
            return images;
        }

        void Cells(int width, int height)
        {
            list_box.Clear();
            list_bitmap.Clear();
            
            int[,] mass = Random(width, height);
            Pictures_to_List(width * height / 2, mass);

            int x = 20, y = 40;
            for(int i=0; i<height;i++)
            {
                for (int j = 0; j < width; j++)
                {
                    MyPictureBox A = new MyPictureBox(x, y);
                    list_box.Add(A);
                    A.Show(this);
                    A.Click();
                    MEMORY_NEW.Global.Sound_Flag = true;
                    MEMORY_NEW.Global.Click_Flag = 0;
                    MEMORY_NEW.Global.time1 = timer1;
                    
                    x = x + 80 + 40; //координаты картинок
                }
                x = 20;
                y = y + 80 + 40;//координаты картинок
            }
            Pictures_to_Boxes();
        }

        void Pictures_to_List(int length, int[,] indexes)
        {
            for (int i = 0; i < length; i++)
            {
                MyBitmap A = new MyBitmap(pictures[i]);
                A.id1 = indexes[i, 0];
                A.id2 = indexes[i, 1];
                list_bitmap.Add(A);
            }
        }

        void Pictures_to_Boxes() //записываем в массив боксов картинки раскаиданные по id
        {
            foreach (MyBitmap bit in list_bitmap)
            {
                list_box[bit.id1].ImageIn(bit.bm);
                list_box[bit.id2].ImageIn(bit.bm);
            }
        }

        void ClearAll()
        {
            foreach (MyPictureBox pb in list_box)
                pb.Delete(this);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //по умолчанию поле 4х4
            this.Width = 483;
            this.Height = 540;
            NewGame();      
        }

        
        private void rulesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //выводим правила игры
            Form Rules = new FormRules();
            Rules.Show();
        }

        private void aboutProgToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //выводим О программе
            Form About = new AboutBox1();
            About.Show();
        }

        private void выходToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //закрываем программу
            Application.Exit();
        }

        private void легкийУровеньToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //поле 4х4
         
            this.Width = 483;
            this.Height = 540;
            level = "easy";
            легкийУровеньToolStripMenuItem.Checked = true;
            среднийУровеньToolStripMenuItem.Checked = false;
            сложныйУровеньToolStripMenuItem.Checked = false;
            NewGame();
        }

        private void среднийУровеньToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //поле 6х4
           
            this.Width = 728;
            this.Height = 520;
            level = "average";
            среднийУровеньToolStripMenuItem.Checked = true;
            легкийУровеньToolStripMenuItem.Checked = false;
            сложныйУровеньToolStripMenuItem.Checked = false;
            NewGame();
        }

        private void сложныйУровеньToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //поле 6х5
           
            this.Width = 728;
            this.Height = 665;
            level = "hard";
            сложныйУровеньToolStripMenuItem.Checked = true;
            легкийУровеньToolStripMenuItem.Checked = false;
            среднийУровеньToolStripMenuItem.Checked = false;
            NewGame();
        }

        private void добавитьСвоиИзображенияToolStripMenuItem_Click(object sender, EventArgs e) //Окно "Открытие" без внутреннего кода
        {    
            Stream myStream = null;
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.InitialDirectory = "c:\\" ;
            openFileDialog1.Filter = "PNG (*.png)|*.png|JPEG (*.jpg;*.jpeg;*.jpe;*.jfif)|*.jpg;*.jpeg;*.jpe;*.jfif|GIF (*.gif)|*.gif|Все файлы изображений (*.*)|*.*";
            openFileDialog1.FilterIndex = 4 ;
            openFileDialog1.RestoreDirectory = true ;

            if(openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if ((myStream = openFileDialog1.OpenFile()) != null)
                    {
                        using (myStream)
                        {
                            Bitmap temp_pic = new Bitmap(Image.FromFile(@openFileDialog1.FileName), 80, 80);

                            temp_pic.SetResolution(80, 80);
                            pictures[user_pic] = temp_pic;
                            NewGame();

                            if (user_pic < 16)
                                user_pic++;
                            else
                                user_pic = 0;
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                } 
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            int[] mas = new int[2];
            int i = 0;
            int k=0;

            foreach (MyPictureBox pb in list_box)
            {

                if (pb.opened == true)
                {
                    mas[k] = i;
                    k++;
                }
                i++;
            }

            if (list_box[mas[0]].img_in_box != list_box[mas[1]].img_in_box)
            {
                list_box[mas[0]].Enable();
                list_box[mas[1]].Enable();
                list_box[mas[0]].ImageMem();
                list_box[mas[1]].ImageMem();    
            }
            else
            {
                win=win+2;
                playSound(MEMORY_NEW.Global.Sound_Flag, "match");
            }

            list_box[mas[0]].opened = false;
            list_box[mas[1]].opened = false;

            timer1.Enabled = false;
            MEMORY_NEW.Global.Click_Flag = 0;
            if (win == i)
            {
                playSound(MEMORY_NEW.Global.Sound_Flag, "win");
                MessageBox.Show("Поздравляем! Вы прошли уровень!");
                win = 0;
            }
        }

        public void playSound(bool flag, string strSwitch)
        {
            if (flag == true)
            {
                switch (strSwitch)
                {
                    case "match":
                        SoundPlayer SameCards = new SoundPlayer();
                        SameCards.Stream = MEMORY.Properties.Resources.match;
                        SameCards.Play();
                        break;
                    case "win":
                        SoundPlayer finGame = new SoundPlayer();
                        finGame.Stream = MEMORY.Properties.Resources.Win;
                        finGame.Play();
                        break;
                }
            }
                flag = false;
            }

        private void обычныйToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MEMORY_NEW.Global.Sound_Flag = true;
        }

        private void безЗвукаToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MEMORY_NEW.Global.Sound_Flag = false;
        }

        private void новаяИграToolStripMenuItem_Click(object sender, EventArgs e)
        {
            NewGame();
        }

        }

    }

